/*
 * Copyright (c) 2001 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.p4eclipse.ui.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;

import net.sourceforge.p4eclipse.core.PerforceRepositoryProvider;
import net.sourceforge.p4eclipse.core.Policy;
import net.sourceforge.p4eclipse.core.api.PerforceUtil;
import net.sourceforge.p4eclipse.core.resources.RemoteFolder;
import org.eclipse.core.internal.resources.ProjectDescription;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.actions.TeamAction;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

/**
  * @version 	1.0
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class AddToWorkspaceAction extends TeamAction
{

	/*
	 * @see TeamAction#isEnabled()
	 */
	protected boolean isEnabled() 
		throws TeamException
	{
		RemoteFolder[] folders = getSelectedRemoteFolders();						
		return folders.length > 0;
	}

	/*
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action)
	{
		run(
			new WorkspaceModifyOperation()
			{
				public void execute(IProgressMonitor monitor)
					throws InvocationTargetException, InterruptedException
				{
					try 
					{
						RemoteFolder[] folders = getSelectedRemoteFolders();
						for (int i = 0, length = folders.length; i < length; i++)
						{
							IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(folders[i].getName());
							if (project.exists())
							{
								Policy.assertTrue(false); // Not yet implemented.
							}
							else
							{
								IProjectDescription projectDescription = new ProjectDescription();
								projectDescription.setName(project.getName());
								projectDescription.setLocation(folders[i].getLocation());
								
								project.create(projectDescription, monitor);								
								PerforceUtil.sync(folders[i].getLocation().toFile(), "#head", monitor);
								
								if (!project.isOpen())
									project.open(monitor);
								else
									project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

								PerforceRepositoryProvider.setSharing(project, monitor);									
							}						
						}
					} 
					catch(CoreException e) 
					{
						throw new InvocationTargetException(e);
					} 
					catch(TeamException e) 
					{
						throw new InvocationTargetException(e);						
					}
				}	
			}, "Add to Workspace failed.", PROGRESS_DIALOG);

	}

	private RemoteFolder[] getSelectedRemoteFolders()
	{
		ArrayList resources = null;
		if (!selection.isEmpty())
		{
			resources = new ArrayList();
			for (Iterator elements = ((IStructuredSelection) selection).iterator(); elements.hasNext(); )
			{
				Object next = elements.next();
				
				if (next instanceof RemoteFolder)
				{
					resources.add(next);
					continue;
				}
				else
				if (next instanceof IAdaptable)
				{
					IAdaptable a = (IAdaptable) next;
					Object adapter = a.getAdapter(RemoteFolder.class);
					if (adapter instanceof RemoteFolder)
					{
						resources.add(adapter);
						continue;
					}
				}
			}
		}
		
		if (resources != null && !resources.isEmpty())
		{
			RemoteFolder[] result = new RemoteFolder[resources.size()];
			resources.toArray(result);
			return result;
		}
		
		return new RemoteFolder[0];
	}
}
